import {simpleGet, simplePost} from "../../../utils/request";
import {showToastError, showToastSuccess} from "../../../utils/tool";
import {validateMobile} from "../../../utils/validate";
import userAddressService from "../../../service/userAddress";

Page({
    data: {
        nav:{
            title:"编辑地址",
        },
        info:null,
        options:{},
        subLoading:false,
    },
    onLoad: function (options={}) {
        (async () => {
            let info = {}
            if (options.id){
                 info = await userAddressService.find(options.id)
            }
            this.setData({
                info,
                options
            })

        })()
    },

    locationChange(e){
        const location = e.detail
        this.setData({
            [`info.location`]:location,
        })
    },
    submit(e){
        const {info} = this.data
        const form = e.detail.value;//表单提交参数

        //  组装数据
        const post = {...info, ...form}
        post.default = 0

        if (!post.contact) {
            showToastError('联系人必填');
            return false;
        }
        //手机号格式验证
        if (!post.mobile || !validateMobile(post.mobile)) {
            showToastError('手机号错误');
            return false;
        }

        if (!post.location || !post.location.address) {
            showToastError('地址必填');
            return false;
        }

        this.setData({
            subLoading:true,
        })

        const url = info.id ? '/userAddress/edit' : '/userAddress/add'

        simplePost(url, post).then(res => {
            // 修改父页面的数据
            // const eventChannel = this.getOpenerEventChannel()
            // eventChannel.emit && eventChannel.emit('editAddressEvent', {address: res.info});
            //
            showToastSuccess("保存成功", {
                timeout:() => {
                    wx.navigateBack()
                }
            })
        }).catch(() => {
            this.setData({
                subLoading: false,
            })
        })
    }
});
